import styles from './index.module.less'
import ArrowSvg from '@/svg/menu-expend'
import cm from 'classnames'
import { useEffect, useMemo } from 'react'
import { getMessage, readMessage } from '@/api/user'
import { useSetState } from 'ahooks'

const Index = () => {
  const [states, setStates] = useSetState({
    currIndex: 0,
    list: [],
    total: 0,
  })

  // 获取消息
  const fetchMessage = async () => {
    const res = await getMessage({ page: 1, pageSize: 1000 })
    if (!res.code) {
      setStates({
        total: res.data.total,
        list: res.data.list || [],
      })
    }
  }
  useEffect(() => {
    fetchMessage()
  }, [])
  const currMessage = useMemo(() => {
    if (!states.list.length) {
      return {}
    }
    try {
      return states.list[states.currIndex]
    } catch (error) {
      return states.list[0]
    }
  }, [states])

  if (!states.list.length) {
    return
  }

  const switchPrev = () => {
    if (states.currIndex > 0) {
      setStates({ currIndex: states.currIndex - 1 })
    }
  }
  const switchNext = () => {
    if (states.currIndex < states.list.length - 1) {
      setStates({ currIndex: states.currIndex + 1 })
    }
  }

  const readed = async () => {
    const res = await readMessage({ noticeId: currMessage.id })
    if (!res.code) {
      setStates({
        currIndex: 0,
      })
      fetchMessage()
    }
  }
  return states.list.length ? (
    <div className={styles.notify}>
      <div className={cm(styles.notifyMain, currMessage.status === 2 ? styles.redNotify : '')}>
        <div className={styles.textBox}>
          <img src={'/images/' + (currMessage.status === 2 ? 'err.webp' : 'succ.webp')} />
          <span>{currMessage.message}</span>
        </div>
        <span className={styles.read} onClick={readed}>
          已阅
        </span>
      </div>
      <div className={styles.switchInfo}>
        <ArrowSvg
          className={cm(styles.leftSwitch, states.currIndex !== 1 ? styles.disableSwitch : '')}
          onClick={switchPrev}
        />
        <span>
          {states.currIndex + 1}/{states.total}
        </span>
        <ArrowSvg
          className={cm(styles.rightSwitch, states.total <= 1 ? styles.disableSwitch : '')}
          onClick={switchNext}
        />
      </div>
    </div>
  ) : null
}

export default Index
